<?php
/**
 * Login
 *
 * @Description 描述
 * @Author look
 * @CreateTime 2022/2/21
 */

namespace app\admin\controller;

use app\admin\service\AdminService;
use app\common\base\ControllerBase;
use app\common\enums\common\IsDel;
use app\common\enums\common\Status;
use app\common\model\AdminModel;
use app\common\utils\AuthToken;
use app\common\utils\Captcha;
use app\common\utils\ErrorCode;
use think\facade\Config;
use think\facade\Request;

/**
 * 登录
 */
class Login extends ControllerBase {

    public function login() {
        $params = Request::post();
        // 参数校验
        $this->validate($params, [
            'username|用户名称' => 'require',
            'password|密码' => 'require',
            'code|验证码' => 'require',
            'uniqid' => 'require'
        ]);

        // 验证码
        if (Config::get('admin.captcha')) {
            $captcha = new Captcha();
            if (!$captcha->check($params['code'], $params['uniqid'])) {
                $captcha->initialize();
                return $this->error(errorCode:ErrorCode::CAPTCHA_ERROR,
                    data: [
                    'captcha' => $captcha->getData(),
                    'uniqid' => $captcha->getUniqid()
                ]);
            }
        }

        $adminModel = new AdminModel();

        $admin = $adminModel->loadAdminByUsername($params['username']);
        // 查找用户是否存在
        if (!$admin || $admin['is_del'] != IsDel::no->value) {
            return $this->error(errorCode:ErrorCode::USER_PASSWORD_ERROR);
        }
        if ($admin['status'] != Status::yes->value ) {
            return $this->error("用户状态异常");
        }
        // 检查密码是否正确
        $adminService = new AdminService();
        if (!$adminService->checkPassword($params['password'], $admin['password'])) {
            return $this->error(errorCode:ErrorCode::USER_PASSWORD_ERROR);
        }
        // 生成用户token
        $token = (new AuthToken())->generateToken([
            'admin_id' => $admin['id']
        ]);
        // 获取用户角色信息
        $admin_roles = $adminService->getRolesByAdmin($admin['id']);
        // 获取用户权限目录
        $menus = $adminService->getMenusByRoles($admin_roles);
        // 剔除用户密码数据
        $admin['token'] = $token;
        $admin['roles'] = $admin_roles;
        $admin['menus'] = $menus;
        unset($admin['password']);
        return $this->success($admin, msg: "登录成功");
    }

    public function verifyCode() {
        $captcha = (new Captcha())->initialize();
        return $this->success([
            'captcha' => $captcha->getCode(),
            'uniqid' => $captcha->getUniqid(),
        ]);
    }

}